'''
医保无忧百万医疗险（2019尊享版）
'''

import sys
import warnings
warnings.filterwarnings('ignore')
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from urllib.parse import  urlencode
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "医保无忧百万医疗险（2019尊享版）"
    # 生成产品数据
    def genProductInfo(self):

        plan = {
            # 年龄段
            "year":[str(i) for i in range(0,61)],
            #有无社保
            "socialSec":["Y","N"],
            #保障金额
            "money":["1000000","2000000","6000000"],
            #保障期限
            "expire":["1年"]
        }
        for v in product( plan["year"],plan["socialSec"],plan["money"],plan["expire"]):

            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format( v[0],v[1],v[2],v[3]))
            self.mysql._conn.commit()
            print( domain[self.name]["insert_sql"].format( v[0],v[1],v[2],v[3]) )

    #执行爬虫
    def requestJson(self,dt=None):

        data = {

            "pageName": "productAdd",
            "goods_id": "62564",
            "merchant_id": "B2C",
            "toubaoli_money":"",
            "productCode": "201910251000001",
            "productId": "ad750b93 - 22d3 - 47ee - a3e8 - f16f73386d57",
            "riskCode": "201910251000000",
            "productName": "医保无忧百万医疗险（2019尊享版）",
            "insuredPrice": "729.00",
            "insured.birthday":"",
            "templateType": "1",
            "employee_id":"",
            "channel": "GWSC - MENU - A13",
            "empNo":"",
            "newsCode":"",
            "twoMonthInsuredPrice":"",
            "loginUserId":"",
            "insured.age": "0" + dt["year"] if int(dt["year"])<10 else dt["year"],
            "policy.amount": int(dt["money"][::3])//2,
            "policy.planType": "01" if dt["socialSec"]=="Y" else "02",
            "policy.dateRemark": "1",
            "person.mobilenum": "承保短信将发送至您的手机"

        }

        payload = urlencode( data ).replace("+","")


        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and "计算保费成功" in r.text :


            price = Helper.decimalParse( r.json()["totalPremium"])

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

            print("产品价格更新失败:", dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)